import Taro, {Component} from '@tarojs/taro'
import { Text, View } from '@tarojs/components'
import { calcSurplusTime } from '@/utils/utils'
import './index.scss'

interface IProps {
  seconds: number
  onTimeUp?: any
}

const formatNum = num => (num <= 9 ? `0${num}` : `${num}`)

export default class Index extends Component<IProps, {}> {
  state: any
  timer: any
  seconds: any

  static options = {
    addGlobalClass: true
  }

  constructor(props) {
    super(...arguments)
    this.timer = undefined
    this.seconds = props.seconds
    const time = calcSurplusTime()
    this.state = {
      time
    }
  }

  componentDidMount() {
    this.setTimer()
  }

  componentDidShow() {
    this.setTimer()
  }

  componentDidHide() {
    this.clearTimer()
  }

  componentWillUnmount() {
    this.clearTimer()
  }

  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.props) === JSON.stringify(nextProps)) {
      return false
    }
    this.seconds = nextProps.seconds
    this.clearTimer()
    this.setTimer()
  }

  /**
   * 开启倒计时
   */
  setTimer() {
    if (!this.timer) this.countdown()
  }

  /**
   * 清除计时器
   */
  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer as number)
      this.timer = undefined
    }
  }

  /**
   * 倒计时
   */
  countdown() {
    const time = calcSurplusTime(this.seconds)

    this.setState({
      time
    })
    this.seconds--

    if (this.seconds < 0) {
      this.clearTimer()
      this.props.onTimeUp && this.props.onTimeUp()
      return
    }

    this.timer = setTimeout(() => {
      this.countdown()
    }, 1000)
  }

  render() {
    const { time } = this.state
    return (<View className='goods-count-down bnn-number '>
      <Text className='count-down__box'>{formatNum(time.hours)}</Text>:
      <Text className='count-down__box'>{formatNum(time.minutes)}</Text>:
      <Text className='count-down__box'>{formatNum(time.seconds)}</Text>
    </View>)
  }
}
